<script setup>
import ImportEmailItemList from '@/views/email/item/index'
import {CircleCheck, DocumentChecked, UploadFilled, InfoFilled} from '@element-plus/icons-vue'
import {getToken} from '@/utils/auth'
import {sendEmailByImportHistoryIds} from "@/api/email/history.js";

const props = defineProps({
  dialogVisible: {
    type: Boolean,
    required: true,
    default: false,
  },
});

const emits = defineEmits(['update:dialogVisible', 'close'])
const {proxy} = getCurrentInstance();

const handleValueChange = (value) => {
  emits('close')
  emits('update:dialogVisible', value)
}

const activeIndex = ref(1);
const loading = ref(false);

/** 下载模板操作 */
const downloadTemplate = () => {
  proxy.download(
      'email/import/history/importTemplate',
      {},
      `邮件导入模板.xlsx`
  )
}

/*** 用户导入参数 */
const uploadConfig = ref({

  // 是否禁用上传
  isUploading: false,

  // 设置上传的请求头部
  headers: {Authorization: 'Bearer ' + getToken()},
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/email/import/history/importData',
})

const uploadRef = ref(null)
const hasFiles = ref(false);
// 文件上传进度
const handleFileUploadProgress = (event, file, fileList) => {

}

const uploadMsg = ref('恭喜您，数据已全部导入成功！共 1 条，数据如下：')
const mailImportHistory = ref({
  mailImportHistoryId: '0',
})

// 文件上传成功
const handleFileSuccess = (response, file, fileList) => {
  console.log('response', response)
  const {msg, code, data} = response
  if (code === 200) {
    uploadRef.value.handleRemove(file)
    uploadMsg.value = data.msg
    mailImportHistory.value = data.mailImportHistory
    activeIndex.value += 1
  } else {
    proxy.$modal.notifyError(msg)
  }
}

const handleFileChange = (file, fileList) => {
  if (fileList.length > 0) {
    hasFiles.value = true
  }
}
// 文件上传前
const handleFileRemove = (file, fileList) => {
  if (fileList.length === 0) {
    hasFiles.value = false
  }
}

// 取消操作
const handleCancel = () => {
  activeIndex.value = 1
  hasFiles.value = false
  uploadRef.value?.clearFiles()
  uploadMsg.value = ''
  handleValueChange(false)
}

const sendLoading = ref(false)
const handleSendEmail = () => {
  sendLoading.value = true
  const id = mailImportHistory.value.mailImportHistoryId
  sendEmailByImportHistoryIds(id).then((res) => {
    const {msg, code} = res
    if (code === 200) {
      console.log('发送成功')
      sendLoading.value = false
      proxy.$modal.notifySuccess('发送成功')
    } else {
      sendLoading.value = false
      proxy.$modal.notifyError(msg)
    }
  })
  proxy.$modal.notifySuccess('正在发送，请稍后查看邮件')
  handleCancel()
}

// 下一步
const handleNext = () => {
  if (activeIndex.value === 1) {
    if (hasFiles.value) {
      uploadRef.value?.submit()
    } else {
      proxy.$modal.notifyWarning('请至少选择一个文件进行上传')
    }
  } else if (activeIndex.value === 2) {
    activeIndex.value += 1

  } else if (activeIndex.value === 3) {
    handleSendEmail()
  }
}

</script>

<template>
  <el-dialog
      :model-value="dialogVisible"
      @update:modelValue="handleValueChange($event)"
      title="导入邮件"
      width="80%"
      destroy-on-close
      center
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
  >
    <el-steps class="mb-4"
              :space="200"
              :active="activeIndex"
              simple
    >
      <el-step title="上传导入文件" :icon="UploadFilled"></el-step>
      <el-step title="确认发信内容" :icon="DocumentChecked"></el-step>
      <el-step title="完成" :icon="CircleCheck"></el-step>
    </el-steps>

    <div v-if="activeIndex === 1" class="upload-mail">
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="uploadConfig.headers"
          :action="uploadConfig.url"
          :disabled="uploadConfig.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          :auto-upload="false"
          drag
      >
        <el-icon class="el-icon--upload">
          <upload-filled/>
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link
                type="primary"
                :underline="false"
                style="font-size: 12px; vertical-align: baseline"
                @click="downloadTemplate"
            >
              下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
    </div>
    <div v-if="activeIndex === 2 && mailImportHistory.mailImportHistoryId !== '0'" class="mail-content">
      <el-descriptions class="descriptions" title="提示信息">
        <div class="sign">
          <InfoFilled style="width: 2em; height: 2em; margin: 0 8px 0 2px"/>
          <span class="link-name" style="margin-left: 10px">{{ uploadMsg }}</span>
        </div>
      </el-descriptions>

      <ImportEmailItemList
          v-model:mailImportHistoryId="mailImportHistory.mailImportHistoryId"
          :tableHideItems="['sendEmail', 'lastSendTime', 'sendNumber', 'status', 'remark', 'code', 'fileName']"
          :showSearch="false"
          :showSend="false"
          :showPagination="false"
      ></ImportEmailItemList>
    </div>

    <div v-if="activeIndex === 3">
      <el-row>
        <el-col :sm="24" :lg="24">
          <el-result
              icon="success"
              title="确认完成"
              sub-title="确认完成后，点击一键发送，将自动发送邮件给收件人，也可以稍后发送。"
          >
            <template #extra>

            </template>
          </el-result>
        </el-col>
      </el-row>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="activeIndex !== 3" :loading="loading" @click="handleCancel"> 取消</el-button>
        <el-button v-else type="primary" :loading="loading" @click="handleCancel"> 稍后发送</el-button>
        <el-button v-if="activeIndex !== 3" type="primary" @click="handleNext" :loading="loading"> 下一步</el-button>
        <el-button v-else type="primary" @click="handleNext" :loading="sendLoading"> 一键发送</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.mail-content {
  .descriptions {
    margin: 20px 0;
  }

  .sign {
    position: relative;
    display: flex;
    align-items: center;
  }
}
</style>
